package org.zj.springstyle.mvc.util;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.zj.springstyle.mvc.parseXml.XMLBeans;

import java.io.File;
import java.util.*;

/**
 * Created by zhaoji on 14/12/24.
 */
public class parseXMLUtil {

    public static Map<String,XMLBeans>   parseStrutsXml(String xmlPath)throws Exception{
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(new File(xmlPath));
        Element root = document.getRootElement();
        Map<String,XMLBeans> rMap = new HashMap<String, XMLBeans>();
        Element actionMapping = root.getChild("action-mapping");
        List<Element> actions = actionMapping.getChildren();
        for(Element el : actions){
            XMLBeans xmlBeans = new XMLBeans();
            String name = el.getAttributeValue("name");
            String type = el.getAttributeValue("type");
            String path = el.getAttributeValue("path");
            xmlBeans.setBeanName(name);
            xmlBeans.setActionClass(type);
            xmlBeans.setPath(path);
            Element actionForm = root.getChild("formbeans");
            List<Element> actionForms = actionForm.getChildren();
            for(Element actionFormE : actionForms){
                if(name.equals(actionFormE.getAttributeValue("name"))){
                    String formclass = actionFormE.getAttributeValue("class");
                    xmlBeans.setFormClass(formclass);
                    break;
                }
            }
            List<Element> forwords = el.getChildren();
            Map<String,String> map = new HashMap<String,String>();
            for(Element x:forwords){
                String fname = x.getAttributeValue("name");
                String fvalue = x.getAttributeValue("value");
                map.put(fname,fvalue);
                xmlBeans.setMap(map);
            }
            rMap.put(path,xmlBeans);
        }
        return rMap;
    }



}
